<script setup>
import {
    Edit, Delete, Link, Download,
} from '@element-plus/icons-vue'
import axios from 'axios';
import { ref } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus'
import {
    addstaffservice, deletestaffservice, updatestaffservice, getAllservice,
    uploadfileservice, getloadfilenameservice, loadfileservice,
} from '@/api/book.js'

//控制添加分类弹窗
const dialogVisible = ref(false)
//分页条数据模型
//const pageNum = ref(1)//当前页
const total = ref(20)//总条数
//const pageSize = ref(3)//每页条数
//文章分类数据模型

//定义变量，控制标题
const title = ref('')
const title2 = ref('上传附件')
//交通路线列表数据模型
const majors = ref([
    { id: 11 }, { id: 23 }
])

const formref = ref(null); //表单校验
//与后端交互的json数据
const pathmodel = ref({
    name: null,
    weight: null,
    model: null,
    cycle: null,
    size: null,
    comment: null,
    type: '单体设备'
})

const findmodel = ref({
    pageNum: 1,
    pageSize: 5,
    str: '',
    findType: '单体设备'
})
const stafflist = async () => {
    console.log(findmodel.value);
    let result = await getAllservice(findmodel.value);
    console.log(result);
    total.value = result.data.total;
    majors.value = result.data.items;
}
stafflist();
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    findmodel.value.pageSize = size;
    stafflist();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    findmodel.value.pageNum = num;
    stafflist();
}
const cleardata = () => {
    findmodel.value.str = ''
}
//表单校验
const rules = {
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
    ],
    weight: [
        { required: true, message: '请输入重量', trigger: 'blur' },
    ],
    model: [
        { required: true, message: '请输入型号', trigger: 'blur' },
    ],
    cycle: [
        { required: true, message: '请输入交货周期', trigger: 'blur' },
    ],
    size: [
        { required: true, message: '请输入尺寸', trigger: 'blur' },
    ],
    comment: [
        { required: true, message: '请输入备注', trigger: 'blur' },
    ],
}
const add = () => {
    pathmodel.value.name = null
    pathmodel.value.weight = null
    pathmodel.value.model = null
    pathmodel.value.cycle = null
    pathmodel.value.size = null
    pathmodel.value.comment = null
    dialogVisible.value = true
    title.value = findmodel.value.findType + '录入'
}
const addstaff = async () => {
    console.log(pathmodel.value);
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            let result = await addstaffservice(pathmodel.value);
            if (result.code == 0) {
                ElMessage.success("添加成功")
                dialogVisible.value = false;
                stafflist();
            }
            else ElMessage.error(result.message ? result.message : '添加失败')
        }
    });
}
const updatestaff = async () => {
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            let result = await updatestaffservice(pathmodel.value);
            if (result.code == 0) {
                ElMessage.success("修改成功")
                dialogVisible.value = false;
                stafflist();
            }
            else ElMessage.error(result.message ? result.message : '修改失败')

        }
    });

}

//删除分类
const del = (row) => {
    ElMessageBox.confirm(
        '你确认删除该条信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户点击了确认
            let result = await deletestaffservice(row.id)
            if (result.code != 0) ElMessage.error(result.message ? result.message : '删除失败')
            else ElMessage.success('删除成功')
            //再次调用getAllCategory，获取所有文章分类
            stafflist();
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
//展示编辑弹窗
const showDialog = (row) => {
    title.value = findmodel.value.findType + '编辑';
    dialogVisible.value = true;
    //数据拷贝
    pathmodel.value.name = row.name;
    pathmodel.value.weight = row.weight;
    pathmodel.value.size = row.size;
    pathmodel.value.cycle = row.cycle;
    pathmodel.value.comment = row.comment;
    pathmodel.value.model = row.model;
    //扩展i的属性，将来需要传递给后台，完成分类的修改
    pathmodel.value.id = row.id;
}
const addorupdate = async () => {
    console.log(title.value);
    if (title.value == '单体设备录入' || title.value == '备品备件录入' || title.value == '设备成套录入') {
        addstaff();
    }
    else {
        updatestaff();
    }
}
const activeTab = ref('first'); // 当前激活的标签页
const handleTabClick = (tab) => {
    cleardata();
    findmodel.value.findType = tab.props.label;
    pathmodel.value.type = tab.props.label;
    stafflist();
};


const fileList = ref([]);
const handleChange = (file, newFileList) => {
    fileList.value = newFileList;
    console.log('Selected files:', fileList.value);
};
const elseid = ref();
const uploadfile = async () => {
    const formData = new FormData();
    fileList.value.forEach(fileItem => {
        formData.append('files', fileItem.raw);
    })
    const formDataArray = Array.from(formData.entries());
    console.log(formDataArray);
    let result = await uploadfileservice(formData, elseid.value)
    if (result.code == 0) {
        ElMessage.success("上传成功")
        dialogVisibleupload.value = false;

    }
    else ElMessage.error(result.message ? result.message : '上传失败')
};
const dialogVisibleupload = ref(false);
const showDialogupload = (row) => {
    fileList.value = [];
    dialogVisibleupload.value = true;
    elseid.value = row.id;
}
const downloadfilesingle = async (filename, delay) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            const link = document.createElement('a');
            link.href = `http://localhost:8080/downloadfile/${filename}`;
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            resolve();
        }, delay);
    });
}
const download = async (row) => {
    let result = await getloadfilenameservice(row.id)
    let filenames = result.data;
    if (filenames.length == 0) {
        ElMessage.error('没有上传附件')
    }
    else {
        for (let i = 0; i < filenames.length; i++) {
            console.log(filenames[i]);
            await downloadfilesingle(filenames[i], i * 1000)
        }
    }
}

</script>

<template>
    <el-card class="page-container">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="单体设备" name="first">
                <!-- 搜索表单 -->
                <el-form>
                    <el-form-item label="查询条件:">
                        <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
                        <el-button type="primary" @click="stafflist" style="margin-left: 15px;">搜索</el-button>
                        <el-button @click="cleardata">重置</el-button>
                        <el-button type="primary" @click="add">新增产品</el-button>
                    </el-form-item>
                </el-form>
                <!-- 文章列表 -->
                <el-table :data="majors" style="width: 100%">
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="重量" prop="weight"></el-table-column>
                    <el-table-column label="型号" prop="model"></el-table-column>
                    <el-table-column label="尺寸" prop="size"></el-table-column>
                    <el-table-column label="交货周期" prop="cycle"></el-table-column>
                    <el-table-column label="备注" prop="comment"></el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="{ row }">
                            <el-button :icon="Download" circle plain type="success" @click="download(row)"></el-button>
                            <el-button :icon="Link" circle plain type="info" @click="showDialogupload(row)"></el-button>
                            <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                            <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty description="没有数据" />
                    </template>
                </el-table>
                <!-- 分页条 -->
                <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
                    :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background
                    :total="total" @size-change="onSizeChange" @current-change="onCurrentChange"
                    style="margin-top: 20px; justify-content: flex-end" />
            </el-tab-pane>

            <el-tab-pane label="备品备件" name="second">
                <!-- 搜索表单 -->
                <el-form>
                    <el-form-item label="查询条件:">
                        <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
                        <el-button type="primary" @click="stafflist" style="margin-left: 15px;">搜索</el-button>
                        <el-button @click="cleardata">重置</el-button>
                        <el-button type="primary" @click="add">新增产品</el-button>
                    </el-form-item>
                </el-form>
                <!-- 文章列表 -->
                <el-table :data="majors" style="width: 100%">
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="重量" prop="weight"></el-table-column>
                    <el-table-column label="型号" prop="model"></el-table-column>
                    <el-table-column label="尺寸" prop="size"></el-table-column>
                    <el-table-column label="交货周期" prop="cycle"></el-table-column>
                    <el-table-column label="备注" prop="comment"></el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="{ row }">
                            <el-button :icon="Download" circle plain type="success" @click="download(row)"></el-button>
                            <el-button :icon="Link" circle plain type="info" @click="showDialogupload(row)"></el-button>
                            <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                            <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty description="没有数据" />
                    </template>
                </el-table>
                <!-- 分页条 -->
                <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
                    :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background
                    :total="total" @size-change="onSizeChange" @current-change="onCurrentChange"
                    style="margin-top: 20px; justify-content: flex-end" />
            </el-tab-pane>
            <el-tab-pane label="设备成套" name="third">
                <!-- 搜索表单 -->
                <el-form>
                    <el-form-item label="查询条件:">
                        <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
                        <el-button type="primary" @click="stafflist" style="margin-left: 15px;">搜索</el-button>
                        <el-button @click="cleardata">重置</el-button>
                        <el-button type="primary" @click="add">新增产品</el-button>
                    </el-form-item>
                </el-form>
                <!-- 文章列表 -->
                <el-table :data="majors" style="width: 100%">
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="重量" prop="weight"></el-table-column>
                    <el-table-column label="型号" prop="model"></el-table-column>
                    <el-table-column label="尺寸" prop="size"></el-table-column>
                    <el-table-column label="交货周期" prop="cycle"></el-table-column>
                    <el-table-column label="备注" prop="comment"></el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="{ row }">
                            <el-button :icon="Download" circle plain type="success" @click="download(row)"></el-button>
                            <el-button :icon="Link" circle plain type="info" @click="showDialogupload(row)"></el-button>
                            <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                            <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty description="没有数据" />
                    </template>
                </el-table>
                <!-- 分页条 -->
                <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
                    :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background
                    :total="total" @size-change="onSizeChange" @current-change="onCurrentChange"
                    style="margin-top: 20px; justify-content: flex-end" />
            </el-tab-pane>
        </el-tabs>

    </el-card>

    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="35%">
        <el-form :model="pathmodel" ref="formref" :rules="rules" label-width="81px" style="padding-right: 30px">
            <el-row gutter="20">
                <el-col :span="12">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="pathmodel.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="重量" prop="weight">
                        <el-input v-model="pathmodel.weight"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20">
                <el-col :span="12">
                    <el-form-item label="型号" prop="model">
                        <el-input v-model="pathmodel.model"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="尺寸" prop="size">
                        <el-input v-model="pathmodel.size"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20">
                <el-col :span="12">
                    <el-form-item label="交货周期" prop="cycle">
                        <el-input v-model="pathmodel.cycle"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="备注" prop="comment">
                <el-input type="textarea" :rows="4" v-model="pathmodel.comment" style="width: 400px"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addorupdate"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogVisibleupload" :title='title2' width="35%">
        <el-upload action="none" class="upload-demo" drag :auto-upload="false" :http-request="httpRequest"
            :file-list="fileList" @change="handleChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisibleupload = false">取消</el-button>
                <el-button type="primary" @click="uploadfile"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>